package lib.wzh.com.libcore.framework.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lib.wzh.com.libcore.framework.request.PageQueryVo;
import org.apache.commons.lang.StringUtils;

/**
 * @Author lib
 * @Date 2021/11/23 17:48
 * @ClassName PageUtil
 * @Version v1.0
 */

public class PageUtil{

    private PageUtil(){}

    public static <T> IPage<T> toPage(PageQueryVo query){
        return toPage(query, null, false);
    }

    public static <T> IPage<T> toPage(PageQueryVo query, String defaultOrderField, boolean isAsc){
        Page<T> page = new Page<>(query.getPageNum(), query.getPageSize());
        //排序字段
        //防止SQL注入
        String orderField = SQLFilter.sqlInject(query.getSort());
        String order = query.getSortBy();
        //前端字段排序
        if(StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)){
            if(Constant.ASC.equalsIgnoreCase(order)) {
                return  page.addOrder(OrderItem.asc(orderField));
            }else {
                return page.addOrder(OrderItem.desc(orderField));
            }
        }

        //没有排序字段，则不排序
        if(StringUtils.isBlank(defaultOrderField)){
            return page;
        }

        //默认排序
        if(isAsc) {
            page.addOrder(OrderItem.asc(defaultOrderField));
        }else {
            page.addOrder(OrderItem.desc(defaultOrderField));
        }
        return page;
    }

    private static class Constant{
        private static final String ASC = "asc";
    }

}
